import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:guochaoapp/common/constant/api.dart';
import 'package:guochaoapp/common/utils/http_client.dart';
import 'package:guochaoapp/model/address_entity.dart';
import 'package:guochaoapp/model/cart_settle_entity.dart';
import 'package:guochaoapp/model/create_order_entity.dart';
import 'package:guochaoapp/model/default_address_entity.dart';
import 'package:guochaoapp/model/freight_entity.dart';
import 'package:guochaoapp/model/transterpay_entity.dart';
import 'package:guochaoapp/routes/app_pages.dart';
import 'package:guochaoapp/services/user_service.dart';
import 'package:guochaoapp/view/mine/address_page.dart';

import '../../r.dart';
import '../tabbar_controller.dart';

class GCShoppingSettleController extends GetxController {
  UserService userService = Get.find();

  var settleData = CartSettleData();

  var address = AddressDataRecord().obs;

  var freight = FreightData().obs;

  getPaymentPrice() {
    if (settleData.priceTotal == null || freight.value.freightTotal == null) return 0.0;

    double paymentPrice = settleData.priceTotal -
        settleData.userBalance +
        freight.value.freightTotal;

    if (paymentPrice < 0) return 0.0;

    return paymentPrice.toStringAsFixed(2);
  }

  getWeightTotal() {
    double weightTotal = settleData.weightTotal;
    if (weightTotal >= 1000) {
      return (weightTotal / 1000).toStringAsFixed(2) + "吨";
    } else {
      return weightTotal.toStringAsFixed(2) + "千克";
    }
  }

  void requestInitData() {
    EasyLoading.show();
    HttpClient.request<DefaultAddressEntity>(
        url: UserAddrApi.usersDefaultAddr,
        method: Method.GET,
        params: {"uid": userService.userInfo.uid},
        onSuccess: (_, model) {
          if (model.data != null) {
            address.value = model.data;
            HttpClient.request<FreightEntity>(
                url: MallApi.freight,
                method: Method.POST,
                data: {
                  "dealerId": userService.dealerId,
                  "uid": userService.userInfo.uid,
                  "addrId": address.value.addrId
                },
                onSuccess: (_, model) {
                  freight.value = model.data;
                },
                onFailed: (err) {
                  EasyLoading.showError(err);
                });
          }
          EasyLoading.dismiss();
        },
        onFailed: (err) {
          EasyLoading.showError(err);
        });
  }

  Future<void> chooseAddress() async {
    var data = await Get.to(GCAddressPage());
    if (data != null) {
      address.value = data;
      EasyLoading.show();
      HttpClient.request<FreightEntity>(
          url: MallApi.freight,
          method: Method.POST,
          data: {
            "dealerId": userService.dealerId,
            "uid": userService.userInfo.uid,
            "addrId": address.value.addrId
          },
          onSuccess: (_, model) {
            freight.value = model.data;
            EasyLoading.dismiss();
          },
          onFailed: (err) {
            EasyLoading.showError(err);
          });
    }
  }

  void jumpToList(List<CartSettleDataItemList> itemList) {
    Get.toNamed(Routes.SHOPPING_LIST, arguments: itemList);
  }

  void submitOrder() {
    if (address.value.addrId == null) {
      EasyLoading.showError("未选择收货地址");
    }
    EasyLoading.show();
    HttpClient.request<CreateOrderEntity>(
        url: MallApi.create,
        method: Method.POST,
        data: {
          "dealerId": userService.dealerId,
          "uid": userService.userInfo.uid
        },
        onSuccess: (_, model) {
          EasyLoading.dismiss();

          if(model.data.skipPayment == true) {
            requestPayment(model.data.mallOrderNo);
          } else {
            Get.toNamed(Routes.SHOPPING_PAYMENT, arguments: {
              "price" : getPaymentPrice(),
              "mallOrderNo" : model.data.mallOrderNo
            });
          }

        },
        onFailed: (err) {
          EasyLoading.showError(err);
        });
  }

  requestPayment(String mallOrderNo) {
    EasyLoading.show();

    HttpClient.request<TransterpayEntity>(
        url: MallApi.payment,
        method: Method.POST,
        data: {
          "mallOrderNo": mallOrderNo,
          "payChannel": "skip",
          "uid": userService.userInfo.uid
        },
        onSuccess: (_, model)  {
          EasyLoading.dismiss();

          Get.toNamed(Routes.PAYMENT_SUCCESS, arguments: {
            "mallOrderNo": mallOrderNo,
            "paymentData": model.data,
            "price": (settleData.priceTotal + freight.value.freightTotal).toString()
          });
        },
        onFailed: (error) {
          EasyLoading.showError(error);
        });
  }
}
